package com.bookstore.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    private static DataSource source;
    static {
        try {
            Properties pros=new Properties();
//            InputStream stream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            InputStream stream = DruidUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            pros.load(stream);
            source= DruidDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = source.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放数据库链接
     * @param conn
     *
     */
    public static void close(Connection conn){
        try {
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放数据库链接
     * @param conn 连接传入
     * @param ps   传入
     * @param rs 传入
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
            if(conn!=null){
                conn.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
